package ch.fusun.baron.basic.client.ui;

import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.swt.widgets.Shell;

import ch.fusun.baron.basic.command.CreateUnitCommand;
import ch.fusun.baron.city.City;
import ch.fusun.baron.client.rmi.ClientService;
import ch.fusun.baron.client.ui.messages.Messages;
import ch.fusun.baron.core.injection.Inject;
import ch.fusun.baron.core.service.UserService;
import ch.fusun.baron.player.api.PlayerService;

/**
 * Action to create a unit
 */
public class CreateUnitTileAction extends AbstractTileAction {

	@Inject
	private PlayerService playerService;
	@Inject
	private UserService userService;
	@Inject
	private ClientService clientService;

	/**
	 * Injection constructor
	 */
	public CreateUnitTileAction() {
	}

	@Override
	public Class<?> getReactionClass() {
		return City.class;
	}

	@Override
	public void execute(Object tile) {
		InputDialog inputDialog = new InputDialog(new Shell(),
				Messages.CreateUnitTileAction_NumerOfUnitsTitle,
				Messages.CreateUnitTileAction_NumberOfUnitsQuestion,
				Messages.CreateUnitTileAction_NumberOfUnitDefault,
				new IInputValidator() {
					@Override
					public String isValid(String newText) {
						try {
							int parseInt = Integer.parseInt(newText);
							if (parseInt <= 0) {
								return Messages.CreateUnitTileAction_Warning;
							}
						} catch (Exception e) {
							return Messages.CreateUnitTileAction_Warning2;
						}
						return null;
					}
				});
		if (inputDialog.open() == InputDialog.OK) {
			clientService.execute(new CreateUnitCommand(playerService
					.getDynasty(userService.getUser()), (City) tile, Integer
					.parseInt(inputDialog.getValue())));
		}
	}

	@Override
	public String getText() {
		return Messages.CreateUnitTileAction_CreateUnitTitle;
	}

}
